package StudyCode.Collections;

import java.util.*;

/**
 * @author lixiaoyao
 */
public class TreeSetTest {

	public static void main(String[] args) {
		SortedSet<Item> parts = new TreeSet<>();
		parts.add(new Item("Toaster", 6666));
		parts.add(new Item("Widget", 4562));
		parts.add(new Item("Modem", 9912));
		System.out.println(parts);

		NavigableSet<Item> sortByDescription = new TreeSet<>(new ComparatorDescription());

		sortByDescription.addAll(parts);
		System.out.println(sortByDescription);
	}
}

class Item implements Comparable<Item> {

	private String description;
	private int partNumber;

	public Item(String description, int partNumber) {
		this.description = description;
		this.partNumber = partNumber;
	}

	public String getDescription() {
		return description;
	}

	@Override
	public String toString() {
		return "[description=" + this.description + ", partNumber=" + partNumber + "]";
	}

	public boolean equals(Object otherObject) {
		if (otherObject == null) {
			return false;
		}
		if (this == otherObject) {
			return true;
		}
		if (getClass() != otherObject.getClass()) {
			return false;
		}
		Item other = (Item) otherObject;
		return Objects.equals(description, other.getDescription()) && partNumber == other.partNumber;
	}

	public int hashCode() {
		return Objects.hash(this.description, this.partNumber);
	}

	@Override
	public int compareTo(Item o) {
		int diff = Integer.compare(this.partNumber, o.partNumber);
		return diff != 0 ? diff : description.compareTo(o.description);
	}
}

class ComparatorDescription implements Comparator<Item> {
	@Override
	public int compare(Item o1, Item o2) {
		return o1.getDescription().compareTo(o2.getDescription());
	}
}
